package xin.marcher.labs.materiel.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.marcher.framework.common.util.spring.PomResourceUtil;

import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

@RestController
@RequestMapping("/read")
public class ProviderController {

    public static final String POM_DIRECTORY = "META-INF/maven!/";
    public static final String TARGET_PATH_PREFIX = "!/";
    public static final String POM_XML = "pom.xml";
    public static final String LOCAL_CLASS_DIRECTORY = "target/classes/";

    public static void main(String[] args) throws IOException {
        resetAppCode();
    }

    /**
     */
    @GetMapping("/jar")
    public String echo() throws IOException {
//        exec();

        resetAppCode();

        return "成功";
    }

    private static void resetAppCode() throws IOException {
        Model pomModel = PomResourceUtil.readPom();
        System.out.println(pomModel.getArtifactId());

    }

    private void exec() throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Enumeration<URL> jsonFiles = classLoader.getResources("xmeta/dataset");
        while (jsonFiles.hasMoreElements()) {
            URL url = jsonFiles.nextElement();
            File xMetaDirectory = new File(url.getPath());
            if (xMetaDirectory.exists()) {
                System.out.println("读取文件");
            } else {
                // 读取 jar
                String jarPath = url.getFile().substring(0, url.getFile().length() - "xmeta/dataset".length() - 2);
                String jarName = FileUtil.getName(jarPath);
                doWithInputStream(Thread.currentThread().getContextClassLoader().getResourceAsStream("BOOT-INF/lib/" + jarName), jarName);
            }
        }
    }

    private void doWithInputStream(InputStream inputStream, String jarName) throws IOException {
        File file = new File("/tmp/" + jarName);
        FileUtils.copyInputStreamToFile(inputStream, file);

        System.out.println(file);
    }
}
